#!/usr/bin/env python3
# _*_ coding:utf-8 _*_
'''
@File    :   detection.py
@Time    :   2022/02/02 15:05:48
@Author  :   chou 
@Version :   1.0
@Contact :   chou2079986882@gmail.com
@Desc    :   None
'''


import requests
import time
import json
import random
from selenium import webdriver
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options
from hashlib import md5
import pymysql
import pandas as pd
from main_project import sql_insert
import sys
headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36"
}
url1 = ' https://wxyqfk.zhxy.net/?yxdm=10623#/login'
url2 = 'https://wxyqfk.zhxy.net/?yxdm=10623#/clockIn'


def login():
    global data_login
    data_login = {
        "Name": stu_name,
        "PassWord": stu_sign_password,
        "UserType": "1",
        "XGH": stu_xgh,
        "YXDM": "10623"
    }
    login_url = "https://wxyqfk.zhxy.net/?yxdm=10623#/login"
    # 登陆
    s = requests.Session()
    s.post(login_url, data=data_login, headers=headers)
    # post登陆页面
    login_result = s.post("https://yqfkapi.zhxy.net/api/User/CheckUser")
    print(login_result)
    return s



# ddddocr接口
def new_ocr():
    pic1 = requests.get('https://yqfkapi.zhxy.net/api/common/getverifycode')
    tex1 = pic1.content
    tex2 = bytes.decode(tex1)
    if json.loads(tex2)['info'] == '非法访问！':
        print(tex2)
        sys.exit(1)
    tex3 = json.loads(tex2)['data']['img']
    key = json.loads(tex2)['data']['key']
    url = 'data:image/png;base64,' + tex3
    # print(url)
    # print(qr_key)
    # 1.识别验证码
    img_url = url
    from ddddocr_NB import free
    from urllib.request import urlretrieve
    urlretrieve(img_url, './qrcode_temp.png')
    filepath = "./qrcode_temp.png"
    code = free(filepath)
    # code="1234"
    print(code)
    print("调用了免费接口（ddddocr接口）")
    return key, code


# post数据部分
def health_daka(s, key, code):
    data_health = {
        "UID": stu_uid,
        "UserType": "1",
        "JWD": JWD,
        "key": key,
        "code": code,
        "ZZDKID": "37",
        "A1": "正常",
        "A4": "无",
        "A2": "全部正常",
        "A3": Place,
        "A11": "不在校",
        "A12": "未实习",
        "A13": "低风险区",
        "YXDM": "10623",
        "version": "v1.3.2"
    }

    # for i in range(2):
    health_url = 'https://wxyqfk.zhxy.net/?yxdm=10623#/clockIn'
    s.post(health_url, headers=headers)
    health_result = s.post('https://yqfkapi.zhxy.net/api/ClockIn/Save', data=data_health, headers=headers)


# 浏览器操作部分driver = webdriver_holdon()
def webdriver_holdon():
    print("开始操作浏览器")
    chromedriver1 = "./chromedriver"
    options = Options()
    options.add_argument('--no-sandbox')
    options.add_argument('--headless')  # 无头参数
    options.add_argument('--disable-gpu')
    # 启动浏览器
    driver = Chrome(executable_path=chromedriver1, options=options)
    print("浏览器设置完成")

    # driver = webdriver.Chrome(chrome_options=chrome_options,executable_path=chromedriver)
    print("打开浏览器成功")
    time.sleep(1)
    driver.get("https://wxyqfk.zhxy.net/?yxdm=10623#/login")
    time.sleep(2)
    XGH = driver.find_element_by_xpath(
        '''//input[starts-with(@placeholder,'请输入学号')]''')
    XGH.click()
    XGH.send_keys(data_login['XGH'])
    print("输入了学号:"+data_login['XGH'])
    Name = driver.find_element_by_xpath(
        '''//input[starts-with(@placeholder,'请输入姓名')]''')
    Name.click()
    Name.send_keys(data_login['Name'])
    print("输入了姓名:"+data_login['Name'])
    Password = driver.find_element_by_xpath(
        '''//input[starts-with(@placeholder,'请输入密码')]''')
    Password.click()
    Password.send_keys(data_login['PassWord'])
    print("输入了密码:"+data_login['PassWord'])
    time.sleep(1)
    login_button = driver.find_element_by_xpath(
        '''//button[starts-with(@class,'sign-in-btn')]''')
    login_button.click()
    print("点击了登陆")
    time.sleep(2)
    driver.get("https://wxyqfk.zhxy.net/?yxdm=10623#/clockIn")
    print("进入到-打卡页面成功")
    time.sleep(1)
    return driver


def uid():
    formdata = {
        "YXDM": "10623",
        "UserType": "1",
        "XGH": stu_xgh,
        "Name": stu_name,
        "PassWord": stu_password
    }
    url = "https://yqfkapi.zhxy.net/api/User/CheckUser"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"}
    response = requests.post(url, data=formdata, headers=headers)
    # 使用json()方法，将response对象，转为列表/字典
    json_response = response.json()
    # print(json_response)
    # 获取UID
    UID = json_response['data']['ID']
    # print(UID)
    stu_uid = str(UID)
    return stu_uid


def insert_one():
    # 1.连接
    conn = pymysql.connect(host='localhost', user='daka', password='1234c', db='daka')
    # print(conn)
    if conn:
        print("连接成功")
    else:
        print('连接失败')
    # 2.创建游标
    cursor = conn.cursor()

    # 使用 execute() 方法执行 SQL，如果表存在则删除
    sql = "INSERT INTO fall(stu_name,stu_num,password,email) VALUES('%s','%s','%s','%s')" % (
    stu_name, stu_xgh, password, to_addr)
    cursor.execute(sql)

    cursor.close()
    print("执行完成")

def recode(a):
    # time.sleep(3)
    # 记录日志
    if a == "success":
        print(stu_name + "打卡成功")
        sql_query2 = f"delete from fall where stu_name='{stu_name}'"
        sql_insert(sql_query=sql_query2)
        print("已在fall数据表删除此人数据")
    else:
        print(stu_name + "打卡失败")
        sql_query_de=f"DELETE from fall WHERE(stu_num='{stu_xgh}')"
        sql_insert(sql_query=sql_query_de)
        insert_one()
    try:
        driver.close()
    except:
        print("进入下一个打卡")

    randomInt = random.randint(0, 20)  # 通过函数返回指定闭区间内的随机数
    print("将等待：" + str(randomInt) + " 秒")
    time.sleep(randomInt)  # 通过函数阻塞指定秒数
    #time.sleep(4)



def all_data():
    # 1.连接

    conn = pymysql.connect(host='localhost', user='daka', password='1234c', db='daka')
    sql_query = 'SELECT * FROM fall'
    table = pd.read_sql(sql_query, con=conn)
    conn.close()
    table=table.drop_duplicates(['stu_num','stu_name'],keep='last')
    # print(df)
    return table

def push(text):
    key="PDU3765TBs56dzcIw5d6WcV4Qe7qqo9MNTdREyuB"
    # text="无内容"
    url=f"https://api2.pushdeer.com/message/push?pushkey={key}&text={text}"
    requests.get(url)

def line():
    table= all_data()
    line = table.shape[0]
    return line

if __name__ == '__main__':
    
    c = 0
    if line() ==0:
        import datetime
        now_time=str(datetime.datetime.now())
        push(text=now_time+" 全部打卡完成👍")

    while line() != 0:
        lis = []
        table = all_data()
        for i in range(table.shape[0]):
            data = table.loc[i]
            lis.append(dict(data))
        for i in lis:
            a = "fall"
            # 姓名
            stu_name = str(i['stu_name'])
            # 学号
            stu_xgh = str(i['stu_num'])
            # 密码
            password = str(i['password'])
            stu_password = md5(password.encode('utf8')).hexdigest()

            # JWD = str(i['JWD'])
            # JWD = str("30.77826,103.95662")
            # Place = str("中国四川省成都市西华大学")
            JWD = str(i['jwd'])
            Place = str(i['place'])
            to_addr = str(i['email'])
            # phone = str(int(i['phone']))

            stu_uid = uid()
            if stu_uid:
                print("查询成功")
                stu_sign_password = str(i['password'])  # 登录密码
                # print(stu_name, stu_password, stu_xgh, stu_uid, JWD, Place)
                s = login()
                driver = webdriver_holdon()
                # 检测是否打卡
                try:
                    # time.sleep(2)
                    if driver.find_element_by_class_name('already-title'):
                        print(stu_name + "今天已打卡")
                        driver.close()
                        a = "success"

                    else:
                        time.sleep(1)
                        driver.refresh()
                        driver.find_element_by_class_name("already-title")
                        print(stu_xgh + "今天已打卡")
                        driver.close()
                        a = "success"

                except:
                    try:
                        # 试着调用新的ocr接口如果出错还是用原来的
                        key, code = new_ocr()
                        time.sleep(1)
                        if len(code) == 4 and code.isalnum():
                            health_daka(s, key, code)
                            a = "success"
                            driver.refresh()
                            if driver.find_element_by_class_name('already-title'):
                                print(stu_name + "今天已打卡")
                                # email_send_right(stu_xgh, to_addr)
                                driver.close()
                                a = "success"
                            else:
                                continue
                        else:
                            key, code = new_ocr()
                            time.sleep(1)
                            if len(code) == 4 and code.isalnum():
                                health_daka(s, key, code)
                                a = "success"
                                driver.refresh()
                                if driver.find_element_by_class_name('already-title'):
                                    print(stu_name + "今天已打卡")
                                    # email_send_right(stu_xgh, to_addr)
                                    driver.close()
                                    a = "success"

                                else:
                                    continue
                    except:
                        key, code = new_ocr()
                        time.sleep(2)
                        if len(code) == 4 and code.isalnum():
                            health_daka(s, key, code)
                            a = "success"

                        else:
                            a = 'wrong'

                        driver.close()
            else:
                print("密码错误")
                a = 'wrong'
                break


            try:
                recode(a)
            except:
                print("❗❗❗发生未知错误，暂时为解决")
        
        if c<=3:
            c+=1
        else:
            break
    

